package cn.springcloud.fix.uaa.web.service.impl;

import cn.springcloud.fix.uaa.dao.entity.User;
import cn.springcloud.fix.uaa.dao.mapper.UserMapper;
import cn.springcloud.fix.uaa.web.service.IUserDetailsService;
import cn.springcloud.fix.uaa.web.vo.SocialUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements IUserDetailsService, SocialUserDetailsService {

    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByMobile(String mobile) {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getMobile, mobile));
        // return checkUser(userDetails);
        return null;
    }

    @Override
    public SocialUserDetails loadUserByUserId(String openId) throws UsernameNotFoundException {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getOpenId, openId));
        // return checkUser(userDetails);
        return null;
    }

    /**
     * DaoAuthenticationProvider#retrieveUser
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, username));
        if (user == null) {
            throw new InternalAuthenticationServiceException("用户名或密码错误");
        }
        SocialUser socialUser = new SocialUser();
        socialUser.setAccount(user.getAccount());
        socialUser.setMobile(user.getMobile());
        socialUser.setPassword(user.getPassword());
        return checkUser(socialUser);
    }

    private SocialUser checkUser(SocialUser socialUser) {
        if (socialUser != null && !socialUser.isEnabled()) {
            throw new DisabledException("用户已作废");
        }
        return socialUser;
    }
}
